package mxw.suiye.autopydroid.Server;


import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import mxw.suiye.autopydroid.util.MyHandler;
import mxw.suiye.autopydroid.util.MyLock;
import mxw.suiye.autopydroid.util.ThreadUi;
import mxw.suiye.autopydroid.util.ResultData;


/**安卓服务监听**/
public class NetServer implements Runnable {


    private ServerSocket ss;
    private Socket s;

    private BufferedReader reader;
    private OutputStream writer;

    private Handler handler;
    private final MyLock myLock = new MyLock();  //开启同步锁

    private boolean isRunning;

    public void stop() {
        isRunning = false;
        try {
            if (s != null) s.close();
            ss.close();

        } catch (Exception e) {
            Log.d("网络线程", "关闭服务失败！");
            e.printStackTrace();
        }
    }

    private boolean initService() {
        try {
            ss = new ServerSocket(2048);
            isRunning = true;
            ResultData.myLock = myLock; //设置全局锁对象以及回复内容

        } catch (IOException e) {
            Log.e("网络线程", "通信结束");
            e.printStackTrace();
            stop();
            return false;

        }
        return true;
    }

    private void waitForClient() throws IOException {
        Log.d("网络线程", "等待请求");
        s = ss.accept();
        reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        writer = s.getOutputStream();
    }

    private JSONObject getRequest() {
        String out;
        JSONObject json;
        try {
            out = reader.readLine();
            if (out.equals("")) {
                writer.write("数据无效".getBytes());
                return null;
            } else {
                Log.d("网络线程", "收到消息：" + out + "|len:" + out.length());
                json = JSONObject.parseObject(out);
                int msgType = json.getIntValue("type");
                if (msgType == 0) {
                    handler = MyHandler.getAppHandle();
                } else if (msgType == 1) {
                    handler = MyHandler.getAccessibilityHandler();
                } else  {
                    writer.write("数据无效".getBytes());
                    return null;
                }
            }
        } catch (IOException e) {
            return null;
        }
        return json;
    }

    private boolean specialData(JSONObject json) {
        if(json==null) return false;
        int msgType = (int) json.get("type");
        try{
            if (msgType == 1 && handler == null) {
                writer.write("无障碍未启动".getBytes());
                return false;
            }
        } catch (IOException e){
            Log.d("网络线程", "目标关闭");
        }
        return true;
    }

    private Message buildMessage(JSONObject json) {
        // 构造消息
        Message msg = handler.obtainMessage();
        msg.what = -1;
        if (json.containsKey("payload")) {
            JSONObject payload = json.getJSONObject("payload");
            assert payload != null;
            msg.what = payload.getIntValue("id");
            msg.obj = payload;
        }
        return msg;
    }

    private void sendMessage(Message msg) {
        //发送消息
        handler.sendMessage(msg);
    }

    private void reply(){
        try {
            synchronized (myLock){
                myLock.wait();
                writer.write(myLock.getData().getBytes());
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        if (!initService()) {
            ThreadUi.toast("服务未启动");
            return;
        }
        while (isRunning) {
            // 等待客户
            try {
                waitForClient();
            } catch (IOException e) {
                Log.d("网络线程", "已退出");
                return;
            }
            // 取得客户
            JSONObject json = getRequest();
            // 判断消息类型，已知类型才继续
            if (!specialData(json)) continue;
            // 构造消息
            Message msg = buildMessage(json);
            // 内部消息动作处理
            sendMessage(msg);
            //
            if(json.getIntValue("result")==1){
                reply();
            }
        }
    }
}
